<template>
  <div class="container clearfix">
    <div class="current-province"
         @tap="sellect_current()">
      <img src="https://h5.ameimeika.com/mp_images/mp_2.4/search/dingwei.png"
           mode="widthFix"
           alt=""
           class="icon">
      当前定位：<span class="tip">{{current_province}}</span>
    </div>
    <div class="title">
      所有省份
    </div>
    <ul class="province-list">
      <li class="list-item"
          :class="{'active':item.active==true}"
          v-for="(item, index) in province_arr"
          :key="index"
          @tap="select_province(item)">
        {{item.name}}
      </li>

    </ul>
  </div>
</template>

<script>
import common from "@/assets/js/mmk_common.js";
export default {
  data () {
    return {
      province_arr: [],
      current_province: "湖北省",
      selected_province: "",
      type: 0
    };
  },
  methods: {
    get_data () {
      wx.showLoading({
        title: "加载中", //提示的内容,
        mask: true, //显示透明蒙层，防止触摸穿透,
        success: res => { }
      });
      common.fly_post("api/v4_2/address/index", {
        is_open: 1
      }, result => {
        wx.hideLoading();
        let res = result.data;
        if (res.status_code == 0) {
          res.data.forEach(element => {
            if (this.selected_province - 0 == element.id) {
              element.active = true;
            }
          });
          this.province_arr = res.data;
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
            duration: 2000,
            mask: false
          });
        }
      })
    },
    select_province (item) {
      let arr = [...this.province_arr];
      arr.forEach(element => {
        if (element.id == item.id) {
          element.active = true;
        } else {
          element.active = false;
        }
      });
      this.province_arr = arr;
      wx.setStorageSync(
        "province_info",
        JSON.stringify({
          province_name: item.name,
          province_id: item.id
        })
      );
      if (this.type == 1) {
        wx.redirectTo({ url: '/pages/life_beauty/main' });
      } else {
        wx.navigateBack({
          delta: 1 //返回的页面数，如果 delta 大于现有页面数，则返回到首页,
        });
      }

    },
    get_location () {
      let that = this;
      wx.getSetting({
        success: res => {
          if (res.authSetting["scope.userLocation"] === true) {
            // 成功授权
            // 已经授权，不会弹框
            wx.getLocation({
              type: 'gcj02',
              success (res) {
                wx.request({
                  url:
                    "https://api.map.baidu.com/geocoder/v2/?ak=QHRdba4oL7bXA0eVS2v1YdakVHEpXKjk&location=" +
                    res.latitude +
                    "," +
                    res.longitude +
                    "&output=json",
                  data: {},
                  header: {
                    "Content-Type": "application/json"
                  },
                  success: function (res) {
                    that.current_province =
                      res.data.result.addressComponent.province;
                  },
                  fail: function () { }
                });
              },
              fail () {
                wx.showToast({
                  title: "无法获取地理位置",
                  icon: "none",
                  duration: 2000,
                  mask: true
                });
                that.city_name = "武汉";
                that.city_id = 180;
                wx.navigateBack({
                  delta: -10
                });
              }
            });
          } else if (res.authSetting["scope.userLocation"] === false) {
            // 授权弹窗被拒绝
            wx.showToast({
              title: "地理授权已被禁用，请前往设置", //提示的内容,
              icon: "none", //图标,
              duration: 2000, //延迟时间,
              mask: false, //显示透明蒙层，防止触摸穿透,
              success: res => {
                setTimeout(() => {
                  wx.openSetting({
                    success: res => { },
                    fail: res => { }
                  });
                }, 1500);
              }
            });
          } else {
            // 没有弹出过授权弹窗
            wx.authorize({
              scope: "scope.userLocation",
              success () {
                wx.getLocation({
                  type: 'gcj02',
                  success (res) {
                    wx.request({
                      url:
                        "https://api.map.baidu.com/geocoder/v2/?ak=QHRdba4oL7bXA0eVS2v1YdakVHEpXKjk&location=" +
                        res.latitude +
                        "," +
                        res.longitude +
                        "&output=json",
                      data: {},
                      header: {
                        "Content-Type": "application/json"
                      },
                      success: function (res) {
                        that.current_province =
                          res.data.result.addressComponent.province;
                      },
                      fail: function () { }
                    });
                  },
                  fail () {
                    wx.showToast({
                      title: "无法获取地理位置",
                      icon: "none",
                      duration: 2000,
                      mask: true
                    });
                  }
                });
              },
              fail () {
                that.current_province = "湖北省";
              }
            });
          }
        }
      });
    },
    sellect_current () {
      this.province_arr.forEach(val => {
        if (val.name == this.current_province) {
          wx.setStorageSync(
            "province_info",
            JSON.stringify({
              province_name: val.name,
              province_id: val.id
            })
          );
          wx.navigateBack({
            delta: 1 //返回的页面数，如果 delta 大于现有页面数，则返回到首页,
          });
        }
      });
    }
  },
  
  onLoad (options) {
    wx.setNavigationBarTitle({
      title: "选择省份"
    });
    Object.assign(this.$data, this.$options.data());
    if (options.type) {
      this.type = options.type
    }
    let that = this;
    wx.getStorage({
      key: "province_info",
      success: res => {
        let info = JSON.parse(res.data);
        that.selected_province = info.province_id;
        this.get_data();
        this.get_location();
      },
      fail: () => {
        this.get_data();
        this.get_location();
      },
      complete: () => { }
    });
  }
};
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  background-color: rgba(243, 244, 246, 1);
  .current-province {
    margin-top: 1px;
    background-color: #fff;
    height: 44px;
    line-height: 44px;
    padding-left: 15px;
    font-size: 14px;
    font-family: "PingFangSC-Regular";
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    .tip {
      color: #ff383e;
    }
    .icon {
      width: 15px;
      vertical-align: middle;
      margin-right: 6px;
    }
  }
  .title {
    font-size: 12px;
    font-family: "Medium";
    font-weight: 500;
    color: rgba(102, 102, 102, 1);
    line-height: 38px;
    padding-left: 15px;
  }
  .province-list {
    background-color: #fff;
    padding: 10px 15px 0;
    display: flex;
    columns: 3;
    flex-wrap: wrap;
    justify-content: flex-start;
    .list-item {
      width: 108px;
      height: 38px;
      box-sizing: border-box;
      border: 1px solid #ccc;
      line-height: 38px;
      text-align: center;
      margin-bottom: 10px;
      font-size: 13px;
      font-family: "PingFangSC-Regular";
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      margin-right: 10.5px;
      &:nth-of-type(3n) {
        margin-right: 0;
      }
    }
    .active {
      border-color: #ff383e;
      color: #ff383e;
    }
  }
}
</style>
